<!DOCTYPE html>
<!--
Title: facultimes.html
Author: Joseph Helgeson, Matthew Tanner
Project: Facultimes
This is an Oregon State University project built as a requirement for CS419. 
The project is a collaboration between Matthew Tanner, Arnold Baghomian, and
Joseph Helgeson. 
-->
<html>
<head>
	<meta charset="UTF-8">
	<title>FaculTimes Web Interface</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.css" />
	<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>
	<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
	<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
	<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>

	<link rel="stylesheet" href="pikaday/pikaday.css" />
	<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
	<script src="pikaday/pikaday.js"></script>
	<script src="pikaday/pikaday.jquery.js"></script>

	<style>
		/* make form errors red + on its own line */
		label.error {
			color: red; 
			display: block;
		}
		
		/* stretch buttons */	
		.btn {
			display: block;
		} 
	</style>
	<script> 
		REQUEST_URL = 'http://web.engr.oregonstate.edu/cgi-bin/cgiwrap/tannerm/facultimes/matt/provider.cgi'

		$(document).ready(function() {

			$("#frm3").validate({
				errorPlacement: function (error, element) {
					error.appendTo(element.parent().prev());
				}
			});

			// Select cloning structure adapted from Charlie Griefer's blog 
			// post, found at: 
			// http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements

			// Adds another username select when add button clicked
			$('#frm3btnAdd').click(function() {
				var num = $('.clonedSelector').length / 2;	// array length = # of "clone-able" divs that currently exist
				var newNum	= new Number(num + 1); 		// gives us a # (i.e., index+1) to enumerate the next div being added

				//clone() old element (=div), then set the new element (=div)'s id based on newNum value
				//alert($('#userSelect' + num).html());
				var newElem = $('#userSelect' + num).clone().attr('id', 'userSelect' + newNum); 
				newElem.attr('name', 'name' + newNum);

				//insert the new div after last "clone-able" input field
				$('#nameInputs').append(newElem);
				newElem.selectmenu();
				newElem.selectmenu('refresh');

				// enable the "delete" button (since we now have > 1 elem)
				// $('#frm3btnDel').parent().show();
				$('#frm3btnDel').prop('disabled', false).button('refresh');
				
			});

			// Deletes last username select created when remove button clicked
			$('#frm3btnDel').click(function() {
				var num = $('.clonedSelector').length / 2;	// array length = # of "clone-able" divs that currently exist

				// remove the last element (div) and decrement num (for eval later)
				$('#userSelect' + num).remove(); 
				num--;

				// if only 1 element remains, disable the "remove" button
				if (num == 1) {
					// $('#frm3btnDel').parent().hide();
					$('#frm3btnDel').prop('disabled', true).button('refresh');
				}
			});  

			//initially, disable the "delete" button (since at least 1 username is required)
			if($('.frm3clonedInput').length < 2){
				// $('#frm3btnDel').parent().hide();
				$('#frm3btnDel').prop('disabled', true).button().button('refresh');
			}
		});
	</script>
</head>
<body>
	<!--///////////////// HOMEPAGE /////////////////-->
	<div data-role="page" data-theme="a" id="homePage">
		<div data-role="header">
			<h1>:: Welcome to FaculTimes ::</h1>
		</div>
		<div data-role="content">
			<div data-role="navbar">
				<ul>
					<li><a href="#homePage" class="ui-btn-active ui-state-persist">Instructions</a></li>
					<li><a href="#opt3Page">Query</a></li>
				</ul>								
			</div><!-- end navbar -->

			<!-- Instructions -->
			<h3>Instructions:</h3>
			Enter your query parameters on the Query page.  Depending on the input provided, queries will return information indiciating:<br />
			<ul>
				<li>The availability of any given user (by username) within a specified window,</li>
				<li>All users specified who are available for the entire duration of a specified window, as well as </li>
				<li>The times when all users specified are available within a particular specified window. </li>
			</ul>

			<p>When you are ready to search, select the "Query" button above.</p>

		</div> <!-- end content -->
	</div> <!-- end #homePage -->

	<!--///////////////// OPTIONS PAGE ///////////////-->
	<div data-role="page" data-theme="a" id="opt3Page">
		<div data-role="header">
			<h1>:: FaculTimes Query ::</h1>
		</div>

		<div data-role="content">
			<div data-role="navbar">
				<ul>
					<li><a href="#homePage">Instructions</a></li>
					<li><a href="#opt3Page" class="ui-btn-active ui-state-persist">Query</a></li>
				</ul>								
			</div><!-- end navbar -->

			<!---------Options form---------->
			<h3>Enter Query Information:</h3>
				Enter a username (or usernames) and a time window (using 24-hour 'military time' format), and Facultimes will provide:<br />
				<ul>
					<li> A list of users available for the entire duration of the window, and</li>
					<li> Times within the window when all users are available. </li>
				</ul>
				Results and any error messages will be displayed below.<br/><br/>
				<strong>NOTE</strong>:  If any date or time fields are left blank, the form will complain.  But if 
				<em>all</em> the date and time fields are left blank, the system will use a default window of today's business hours.
				<br/><br/>
				

			<div class="ui-field-contain">
				<form id="frm3" method="post">	
					<div>
					<label for="opt3startwindow"><strong>Window Start Date and Time:</strong></label>
					<fieldset class="ui-grid-b">
						<div class="ui-block-a" style="width:42%">														
							<input id="opt3startwindow" class="startselects" type="text"  placeholder="MM/DD/YYYY"/>
						</div>
						<div class="ui-block-b" style="width:29%">
							<select class="startselects" id="starthours"></select>
						</div>
						<div class="ui-block-c" style="width:29%">
							<select class="startselects" id="startminutes">
								<option value="">MM</option>
								<option value="00">00</option>
								<option value="15">15</option>
								<option value="30">30</option>
								<option value="45">45</option>
							</select>
							<input type="hidden" id="startwindow" name="startwindow">
						</div>
					</fieldset>

					<label for="opt3endwindow"><strong>Window End Date and Time:</strong></label>
					<fieldset class="ui-grid-b">
						<div class="ui-block-a" style="width:42%">	
							<input id="opt3endwindow" class="endselects" type="text" placeholder="MM/DD/YYYY" data-inline="true"/>
						</div>
						<div class="ui-block-b" style="width:29%">
							<select class="endselects" id="endhours"></select>
						</div>
						<div class="ui-block-c" style="width:29%">	
							<select class="endselects" id="endminutes">
								<option value="">MM</option>
								<option value="00">00</option>
								<option value="15">15</option>
								<option value="30">30</option>
								<option value="45">45</option>
							</select>								
							</select>
							<input type="hidden" id="endwindow" name="endwindow">
						</div>
					</fieldset>
					</div>

					<!-- ...and the dynamic bit... -->
					<b<strong>Users to Include in Search:</strong>	
					<div id="nameInputs">
						<select name="name1" id="userSelect1" class="clonedSelector" data-native-menu="true">
						</select>						
					</div>
					<!-- Add/Del buttons -->
					<input class="btn" id="frm3btnAdd" type="button" data-icon="plus" data-iconpos="right" value="Add Another User" />
					<input class="btn" id="frm3btnDel" type="button" data-icon="minus" data-iconpos="right" value="Remove User" />
					<input class="btn" id="opt3submit" name="opt3submit" data-icon="search" data-iconpos="right" type="submit" value="Go" /> 
				</form>
			</div>

			<!---------Results---------->
			<div class="ui-field-contain" id="resultswrapper3">
				<h2 id="resultsheading"></h2>
				<h3 id="statusfield"></h3>
				<h3 id="timesheading"></h3>
				<ul id="timeslist">
				</ul>
				<h3 id="attendeesheading"></h3>
				<ul id="attendeeslist">
				</ul>
			</div>
		</div> 
	</div> 
	<script>
		// todays date in the correct format comes courtesy of stackoverlow
		// http://www.google.com/url?q=http%3A%2F%2Fstackoverflow.com%2Fa%2F4929629%2F2281645&sa=D&sntz=1&usg=AFQjCNFubmqkm4eJTqSPDlwRnEWJ6kucOA
		var today = new Date();
		var dd = today.getDate();
		var mm = today.getMonth() + 1;
		var yyyy = today.getFullYear();
		if(dd<10){
			dd='0'+dd
		}
		if(mm<10) {
   			 mm= '0' +mm
		} 
		today = mm+'/'+dd+'/'+yyyy;
		startwindowdefault = today + " 00:00"
		endwindowdefault = today + " 23:00"
		$('#startwindow').val(startwindowdefault);
		$('#endwindow').val(endwindowdefault);


		//initialize date pickers, format output
		$('#opt3startwindow').pikaday({
			firstday: 1,
			onSelect: function(){
				$('#opt3startwindow').val(this.getMoment().format('L'));
			}
		});
		$('#opt3endwindow').pikaday({
			firstday: 1,
			onSelect: function(){
				$('#opt3endwindow').val(this.getMoment().format('L'));
			}
		});

		if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
			$('.startselects, .endselects').attr('readonly', 'readonly');
		}

		// Populate hour selects (instead of using 24 option tags)
		var select = $("#starthours, #endhours");
		select.append('<option value="">HH</option>')
		for(i=0; i<24; i++){
			if(i < 10)
				hour = "0" + i;
			else hour = i;
			select.append('<option value="'+ hour +'">' + hour + '</option>')
		}

		// Populate username select
		$.getJSON(REQUEST_URL,
			{validusers: 'true'},
			function(data){
			var select = $('#userSelect1');
			select.append('<option value="">Select a User</option>');	
			for(var index in data.validusers){
				var name = data.validusers[index];
				select.append("<option value='"+ name +"'>"+name+"</option>");
				select.selectmenu();
				select.selectmenu( "refresh" );
			}
		});

		// Post form data via ajax and prevent redirect
		$("#frm3").submit( function () { 
			clearResults();
			$("#statusfield").text("Retrieving results....").css('color', 'blue');

			if(($('#opt3startwindow').val() != "") || 
			  ($('#opt3endwindow').val() != "") ||
			  ($('#starthours').val() != "") ||
			  ($('#endhours').val() != "") ||
			  ($('#startminutes').val() != "") ||
			  ($('#endminutes').val() != "")){	
				combineSelects();
			}
			else {
				if($('#starthours').val() == "" && $('#endhours').val() == ""){
					$('#startwindow').val(startwindowdefault);
					$('#endwindow').val(endwindowdefault);		
				}		
			}

			$.post(REQUEST_URL,
				$(this).serialize(),
				function(data){
					$("#statusfield").empty();
					displayOption3(data); 
				},
				'json'
			);
			return false;   
		});	

		// On submit the date, hour and minute selects are combined into hidden inputs
		// startwindow, and endwindow.
		function combineSelects(){
			var date = $('#opt3startwindow').val();
			var hour = $('#starthours').val();
			var min = $('#startminutes').val();
			$('#startwindow').val((date + " " + hour + ":" + min));


			date = $('#opt3endwindow').val();
			hour = $('#endhours').val();
			min = $('#endminutes').val();
			$('#endwindow').val((date + " " + hour + ":" + min));			
		}		

		function clearResults(){
			$("#resultsheading").empty()
			$("#statusfield").empty()
			$("#timesheading").empty();
			$("#timeslist").empty();
			$("#attendeesheading").empty();
			$("#attendeeslist").empty();			
		}
	
		// Display results from form post 
		function displayOption3(data){

			// Display error message if returned
			if(data['error']){
				var error = data['error'];
				$("#statusfield").text(error).css('color', 'red');
				return
			}

			// Otherwise display times:
			$("#resultsheading").text("Results")
			$("#timesheading").text("Times within window when all selected users are available:");	
			if(data['times'].length == 0){
				$("#timeslist").append("<li>No times exist within the specified window when all selected users are available.</li>")
			}
			for(var index in data.times){
				var time = "<li>" + data.times[index].start + " - " + data.times[index].end + "</li>";
				$("#timeslist").append(time);
			}

			// display attendees
			$("#attendeesheading").text("Users available for the entire window:");
			if(data['attendees'].length == 0){
				$("#attendeeslist").append("<li>None of the selected users are available for the entire window.</li>")
			}		
			for(var index in data.attendees){
				var attendee = "<li>" + data.attendees[index].name + "</li>";
				$("#attendeeslist").append(attendee);
			}
		}
	</script>
</body>
</html>
